// pages/opt_user_admin/opt_page/equ_position/equ_position.js
var app = getApp()
//常量数据配置
var ConstantData = require('../../../../../common/constant_data.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hpStatArr:['正常','维修','下线','生产中','疑似丢失','确定丢失'],
    objectHpStatArr: [{ id: 1, name: '正常' }, { id: 3, name: '维修' }, { id: 2, name: '下线' }, { id: 0, name: '生产中' },{id:13,name:'疑似丢失'},{id:10,name:'确定丢失'}],    
    index:0,
    eqNums:'',
    eqIds:'',
    tipStatus:false,
    evtType:0, //0仅做提示
    tipContentColor:'',
    currentHospital:'',         
    homingHospitals:[],
    chairHospitals:[],
    hpPosition:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.removeStorageSync('setPositionHospital');
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
 
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorageSync('setPositionHospital');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  bindPickerHpStatChange: function (e) {
    this.setData({
      index: e.detail.value
    })
  },

  scan:function() {
    var that = this;
    wx.scanCode({
      success: function (res) {
        //记录日志
        // var logData = { reqNumber: 1, optDesc: "桩二维码前缀常量:" + ConstantData.CONSTATNT_DATA.DEVICE_QRCODE_URL_PREFIX };
        // that.connectLog(logData)

        var qrc = '';
        var qrCode = res.result;
        if(!qrCode){
          wx.showToast({
            title: '二维码为空',
            icon: 'none'
          })
          return;
        }
        if (qrCode.indexOf(ConstantData.CONSTATNT_DATA.DEVICE_QRCODE_URL_PREFIX) == 0) {
          //设备二维码
          var rst = qrCode.split('/');
          qrc = rst[rst.length - 1];       
        } else {
          that.setData({
            alertBoxStatus: true,
            alertBoxTipContent: '二维码有误!'
          });
          return
        }
       

        var nophone = app.getUserLoginNoPhone();
        if (nophone == null || nophone == undefined || nophone == 1) {
          wx.setStorageSync('scan_qrc', qrc);
          wx.navigateTo({
            url: '../../../../../pages/login/login?pt=scan',
          })
          return
        }

        console.log("scan-----------qrc=" + qrc)
        console.log("******获取要连接的设备名称")
        that.getHomingPileId(qrc);
      },
      fail: function (res) {
       
      }
    });
  },

  /**
   * 获取归位桩id
   */
  getHomingPileId:function(qrc){
    var that = this;
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_admin/equ_position/get_hid',
        header: header,
        data:{
          qrc:qrc
        },
        success: function (res) {
          console.log("hids---->", res);
          var hids = that.data.eqNums;
          var hidNum = res.data.hid;
          if ((hids + ',').indexOf(hidNum+',')>=0) {
            wx.showModal({
              title: '重复桩号提示',
              content: '已经扫描过' + hidNum + '号桩'              
            });
            
            return;
          }
          if (hids && hidNum > 0) {   
            var endFlg = hids.endsWith(',') || hids.endsWith('，') || hids.endsWith(' ') || hids.endsWith('.') || hids.endsWith('。');   
            hids += (endFlg ? '' : ',') + hidNum;
          }else {
            hids = hidNum;
          }  
          var hospital = wx.getStorageSync('setPositionHospital');
          if(!hospital) {
            hospital = res.data.hospital;
            wx.setStorageSync('setPositionHospital', hospital);
            that.setData({
              currentHospital:'当前所在医院:【'+hospital+'】'
            })
          }
          if (res.data.hospital != hospital) {
            that.setData({
              tipStatus:true,
              evtType:1,
              tipContentColor:"color:red;",
              changeHid:hidNum,
              belongHospital:hospital,
              tipContent:hidNum+'号桩不属于:【'+hospital + "】;而属于:【" + res.data.hospital+"】"
            });           
          }else {            
            that.setData({
              tipStatus: true,
              evtType: 0,
              tipContent: hidNum + '号桩属于:【' + res.data.hospital+'】'
            });           
          }
          console.log("-------------------hids",hids);
          that.setData({
            eqNums: hids
          })
          that.getHomingHospitals();
        }
      })
    });  
  },

  /**
   * 配置设备位置信息
   */
  positionSubmit:function(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value);
    //{"hids":"64","eqids":"","position":"医院某位置"}
    var postData = e.detail.value;
    if(!postData.position) {
      wx.showToast({
        title: '请填写位置信息',
        icon: "none"
      })
      return;
    }
    if(!postData.hids && !postData.eqids) {
      wx.showToast({
        title: '编号不能全为空',
        icon: "none"
      })
      return;
    }

    var reg = /^([0-9]+[,，。.\s]?)+$/;
    if(postData.hids && !reg.test(postData.hids)) {
      wx.showToast({
        title: '归位桩编号格式不对',
        icon:"none"
      })
      return;
    }
    if (postData.eqids && !reg.test(postData.eqids)) {
      wx.showToast({
        title: '轮椅编号格式不对',
        icon: "none"
      })
      return;
    }
    wx.showLoading({
      title: '保存中...',
      mask: true
    }); 
    var that = this;
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_admin/equ_position/update_position',
        header: header,
        data: e.detail.value,
        success: function (res) {
         if(res.data.result == 0) {
           wx.showToast({
             title: '保存成功',
           });
           that.getHomingHospitals();
           that.getChairHospitals();
           getApp().hideLoading();
         }else {
           wx.showToast({
             title: '保存失败',
           })
         }
        }
      })
    });  
  },
  /**
   * 表单重置
   */
  formReset:function() {
    wx.removeStorageSync('setPositionHospital');
    this.setData({
      evtType:0,
      currentHospital:"",
      eqNums:"",
      homingHospitals:[],
      chairHospitals:[],
      hpPosition:''
    })
  },

  /**
   * 记录需要变更归位桩的桩号及变更的医院
   */
  recordNeedChangeBelongHid:function(hid,hospital) {
      
    var that = this;
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_admin/equ_position/record_change_belong',
        header: header,
        data: {
          hid:hid,
          hospital:hospital
        },
        success: function (res) {
          if (res.data.result == 0) {
            wx.showToast({
              title: '变更已标记',
            })
          } else {
            wx.showToast({
              title: '保存失败',
            })
          }
        }
      })
    });  


  },

  /**
   * 提示窗口点击事件
   */
  tipBtnClick:function() {
    if(this.data.evtType == 1) {
        //记录归位桩变更标记
      this.recordNeedChangeBelongHid(this.data.changeHid,this.data.belongHospital);
    }
    this.setData({
      tipStatus:false,
      evtType:0,
      tipContentColor:""
    })
  },

  /**
   * 用户手动输入编号 
   **/ 
  handChangeHid:function(e) {
     this.setData({
       eqNums:e.detail.value
     });  
    this.getHomingHospitals(); 
  },
  handChangeEqId:function(e) {
    this.setData({
      eqIds:e.detail.value
    });
    this.getChairHospitals();
  },
  /**
   * 获取归位桩对应的医院信息
   */
  getHomingHospitals:function() {
    var that = this;
    if (!that.data.eqNums) {
      return;
    }
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_admin/equ_position/homing_hospitals',
        header: header,
        data: {
          hids: that.data.eqNums
        },
        success: function (res) {
          if (res.data.result == 0) {
             that.setData({
               homingHospitals:res.data.data,
               hpPosition: res.data.data[0].hp_position,
               homingStatInfo: res.data.pipleStatInfo
             })
          } else {
            wx.showToast({
              title: '获取失败',
            })
          }
        }
      })
    });  
  },

  /**
   * 获取归位桩对应的医院信息
   */
  getChairHospitals: function () {
    var that = this;
    if (!that.data.eqIds) {
      return;
    }
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_admin/equ_position/chair_hospitals',
        header: header,
        data: {
          eqIds: that.data.eqIds
        },
        success: function (res) {
          if (res.data.result == 0) {
            that.setData({
              chairHospitals: res.data.data,
              homingStatInfo: res.data.pipleStatInfo
            })
          } else {
            wx.showToast({
              title: '获取失败',
            })
          }
        }
      })
    });
  }

})